package com.szwistar.common.comm.yunxin;

import com.szwistar.common.comm.SmsService;
import com.szwistar.common.datastruct.JsonMapper;
import com.szwistar.common.datastruct.JsonObject;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网易云信短信服务
 */
@SuppressWarnings("deprecation")
public class YunxinSmsService implements SmsService {
	protected static final Logger LOG = LoggerFactory.getLogger(YunxinSmsService.class);

	// 发送验证码的请求路径URL
	private static final String URLSendVerify = "https://api.netease.im/sms/sendcode.action";
	// 发送模板消息
	private static final String URLSendNotify = "https://api.netease.im/sms/sendtemplate.action";
	// 随机数
	private static final String NONCE = "123456";
	// 验证码长度，范围4～10，默认为4
	private static final String CODELEN = "6";

	// appId <--> 服务 映射表
	static Map<String, YunxinSmsService> appServiceMap = new HashMap<String, YunxinSmsService>();

	// 获取 APP 服务
	public static SmsService getAppService(String appId) {
		if(appId == null) { return null; }
		return appServiceMap.get(appId);
	}

	// 应用显示名称
	protected String title;
	// appKey
	protected String appKey;
	// appSecret
	protected String appSecret;
	// 默认的验证码发送模板
	protected String defaultVerifyTemplateId;

	public String getTitle() { return title; }
	public String getAppKey() { return appKey; }
	public String getAppSecret() { return appSecret; }

	public YunxinSmsService(String title, String appKey, String appSecret, String defaultVerifyTemplateId) {
		super();
		this.title = title;
		this.appKey = appKey;
		this.appSecret = appSecret;
		appServiceMap.put(appKey, this);
		this.defaultVerifyTemplateId = defaultVerifyTemplateId;
	}

	@SuppressWarnings("resource")
	public JsonObject send(boolean isVerify, String[] tels, String templateId, Map<String, Object> smsParam) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(isVerify ? URLSendVerify : URLSendNotify);

		// 当前时间(秒)
		String curTime = String.valueOf(System.currentTimeMillis() / 1000L);
		// 计算 CheckSum
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, NONCE, curTime);
		// 设置请求的 header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

		try {
			// 设置请求的的参数，requestBody参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();

			if(isVerify) {
				// 是验证短信
				nvps.add(new BasicNameValuePair("mobile", tels[0]));
			} else {
				// 是模板短信
				// 注意参数mobile是有s的，详细参数配置请参考“发送模板短信文档”
				// 参数格式是jsonArray的格式，例如: "['13888888888','13666666666']"
				nvps.add(new BasicNameValuePair("mobiles", JsonMapper.toJson(tels)));
				// 模板参数：是根据模板里面有几个参数，那里面的参数也是jsonArray格式
				nvps.add(new BasicNameValuePair("params", JsonMapper.toJson(smsParam.values())));
			}
			nvps.add(new BasicNameValuePair("templateid", templateId));
			nvps.add(new BasicNameValuePair("codeLen", CODELEN));

			// 参数编码
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

			 // 执行请求
	        HttpResponse response = httpClient.execute(httpPost);

	        /*
	         * 1.打印执行结果，打印结果一般会200、315、403、404、413、414、500
	         * 2.具体的code有问题的可以参考官网的Code状态表
				class SmsVerifyMessage {
					@JsonProperty int code;
					@JsonProperty int msg;
					@JsonProperty String obj;
				}
	         */
	        String json = EntityUtils.toString(response.getEntity(), "utf-8");
			return JsonMapper.fromJson(json);
		} catch(Exception e) {
			return new JsonObject("code", 500);
		}
	}

	@Override
	public boolean send(String[] tels, String templateId, Map<String, Object> smsParam) {
		JsonObject ret = send(false, tels, templateId, smsParam);
		return ret.getInt("code", -1) == 200;
	}

	@Override
	public boolean send(String targetTel, String templateId, Map<String, Object> smsParam) {
		String tels[] = { targetTel };
		return send(tels, templateId, smsParam);
	}

	@Override
	public String sendVerify(String targetTel, String templateId) {
		String tels[] = { targetTel };
		JsonObject ret = send(true, tels, templateId, null);
		return ret.getInt("code", -1) == 200 ? ret.getStr("obj", null) : null;
	}

	@Override
	public String sendVerify(String targetTel) {
		return sendVerify(targetTel, defaultVerifyTemplateId);
	}

	public static void main(String[] args) throws Exception {
		PropertyConfigurator.configure("log4j.properties");

		YunxinSmsService svc = new YunxinSmsService(
				"智辰智能家居",
				"c0f9ee60939cbebe40a1367f8984e3e7",
				"e3470e11d8ce",
				"14878489");

        String code = svc.sendVerify("18612345678", "14878489");
        System.out.println(code);
	}
}

class CheckSumBuilder {
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    // 计算并获取 CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取 md5 值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
}
